package com.cuckoo.mall.thus.start;


import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.widget.RadioGroup;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.bgn.baseframe.base.BaseActivity;
import com.bgn.baseframe.network.bean.TDataBean;
import com.bgn.baseframe.utils.evenbus.MainEvent;
import com.bgn.baseframe.utils.jsontool.GsonUtil;
import com.cuckoo.mall.R;
import com.cuckoo.mall.javabean.TestBean;
import com.cuckoo.mall.test.UploadService;
import com.cuckoo.mall.thus.manager.UserInfoManager;
import com.cuckoo.mall.thus.menuaccount.AccountFragment;
import com.cuckoo.mall.thus.menucart.MenucartFragment;
import com.cuckoo.mall.thus.menufoucs.FoucsFragment;
import com.cuckoo.mall.thus.menuindex.MenuIndexFragment;
import com.cuckoo.mall.thus.utils.DialogHelper;
import com.freshchat.consumer.sdk.beans.User;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;
import java.util.Random;


/**
 * wanglun
 * 2018年3月19日 10:54:26
 */
@Route(path = "/mall/mainActivity", group = "mall")
public class MainActivity extends BaseActivity {

    int i = 1;
    private RadioGroup rg_tab;
    private int selectId = R.id.rb_home;

    //    private MenuIndexFragment homeFragment;
//    private FoucsFragment categoriesFragment;
//    private MenucartFragment cartFragment;
//    private AccountFragment accountFragment;
//    private SupportFragment supportFragment;
    private Fragment currentFragment;


    private final String HOME_FRAGMENT = "home";         // 首页的Fragment
    private final String CATEGORIES_FRAGMENT = "foucs";    // 种类Fragment
    private final String CART_FRAGMENT = "cart";           //购物车的Fragment
    private final String ACCOUNT_FRAGMENT = "accout";       //账户的Fragment

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
        setIsLoadTitleBar(false);
        setContentView(R.layout.activity_main);
        initView();

        //测试分支的代码
//        for (; i < 10; i++) {
//            long time = new Random().nextInt(2000) * 1L;
//            String tag = i + "";
//            UploadService.startUpdateService(this, tag, time);
//        }

    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(MainEvent event) {
        hideLoadingView();
        switch (event.getEventName()) {
            case MainEvent.UPDATE_CART:
                MenucartFragment menucartFragment = (MenucartFragment) getSupportFragmentManager().findFragmentByTag(CART_FRAGMENT);
                if (menucartFragment != null) {
                    menucartFragment.resetFreshState(true);
                }
                break;
            case MainEvent.SHARE_SUCCEED:
                DialogHelper.showShareDialog(getActivity(), getString(R.string.share_succeed), getString(R.string.share_succeed_content), getString(R.string.take_it_now), R.mipmap.share_succeed, new DialogHelper.DialogPressCallBack() {
                    @Override
                    public void whenPressRightButton() {

                        if (UserInfoManager.getInstance().checkTrunLogin()) {
                            ARouter.getInstance().build("/mall/ticketListActivity").navigation();
                        }
                    }
                });
                break;
            case MainEvent.SHARE_FAILD:
                DialogHelper.showShareDialog(getActivity(), getString(R.string.share_faild), getString(R.string.share_faild_contnet), getString(R.string.try_latter), R.mipmap.share_faild, null);
                break;
            //用evenbug在别的页面传递过来调goHomePage会出现chekcBtn错乱的问题，原因不明，规避用newInten去调用goHomePage
        }
    }


    public void goHomePage() {
        rg_tab.check(R.id.rb_home);
    }

    private void initView() {
        //初始化RadioGroup
        rg_tab = findViewById(R.id.rg_tab);
        rg_tab.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                long time = new Random().nextInt(2000) * 1L;
                String tag = i++ + "";
                UploadService.startUpdateService(MainActivity.this, tag, time);
                return;

//                switch (checkedId) {
//                    case R.id.rb_home:
//                        selectId = R.id.rb_home;
//                        replaceFragment(HOME_FRAGMENT);
//                        break;
//                    case R.id.rb_categories:
//
//                        selectId = R.id.rb_categories;
//                        replaceFragment(CATEGORIES_FRAGMENT);
//                        break;
//                    case R.id.rb_cart:
//
//                        if (UserInfoManager.getInstance().checkTrunLogin()) {
//                            selectId = R.id.rb_cart;
//                            replaceFragment(CART_FRAGMENT);
//                        } else {
//                            rg_tab.check(selectId);
//                        }
//                        break;
//                    case R.id.rb_account:
//                        selectId = R.id.rb_account;
//                        replaceFragment(ACCOUNT_FRAGMENT);
//                        break;
//                }

            }
        });
        rg_tab.check(selectId);
    }


    private void replaceFragment(String tag) {
        if (currentFragment != null) {
            getSupportFragmentManager().beginTransaction().hide(currentFragment).commit();
        }
        currentFragment = getSupportFragmentManager().findFragmentByTag(tag);
        if (currentFragment == null) {
            switch (tag) {
                case "home":
                    currentFragment = new MenuIndexFragment();
                    break;
                case "foucs":
                    currentFragment = new FoucsFragment();
                    break;
                case "cart":
                    currentFragment = new MenucartFragment();
                    break;
                case "accout":
                    currentFragment = new AccountFragment();
                    break;
            }
            getSupportFragmentManager().beginTransaction().add(R.id.fl_content, currentFragment, tag).commit();
        } else {
            getSupportFragmentManager().beginTransaction().show(currentFragment).commit();
        }
    }

    @Override
    public void onBackPressed() {
        if ((rg_tab.getCheckedRadioButtonId() == R.id.rb_account || rg_tab.getCheckedRadioButtonId() == R.id.rb_categories) && isLoadingShowing()) {
            hideLoadingView();
        } else {
            moveTaskToBack(true);
        }

    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        if (intent != null && "lang".equals(intent.getStringExtra("action"))) {
            String dataString = intent.getStringExtra("json");
            finish();
            startActivity(new Intent(this, MainActivity.class));
        } else if (intent != null && "home".equals(intent.getStringExtra("action"))) {
            MenucartFragment menucartFragment = (MenucartFragment) getSupportFragmentManager().findFragmentByTag(CART_FRAGMENT);
            if (menucartFragment != null) {
                menucartFragment.resetFreshState(true);
            }
            goHomePage();
        }

    }

//    private void Test() {
////        String data = "howareyou!";
////        String eData = RSAUtil.getencrptString(data);
////        Logger.d("TEST输出e：" + eData);
//        String testString="ngwduA1rTkYNeDuEjpsTMFlxeL/Z/VX1TzXIefiqqr/LhgRc7FWwBiWVw6X+6MNFqdzIE9ORIQJtxqv4pvzSHDbPaWUW6n+UmFhMrMKz+TDzOT/uPvq3COA745El4kSs4OimG7g9uwfl3CzTBmPlUm2iUfo6eX5nx85lkNY1PDW90pu0gtrWlT0L/504687dfuTYUBRjH4XDLBNDWtFJyXlBBSWm1yNTN4lCPzrP/2rcWZx/gG2JTzrWbIFn7UEciFZ18Ax6y/8SlJoUNepp7dbJrfHqlBrvf7hN0IxbmUJiRHMKqqrx/+nGLfQ/YYq2tpd+tLHhc+fUH4nE55xKZw==";
//        String deString=RSAUtil.getdecryptString(testString);
//        Logger.d("TEST输出d：" + deString);
//    }


}
